package database

import (
	"log"
	"user-agent/database/schema"
	"user-agent/utils"

	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var engine *xorm.Engine

func InitDriver() error {
	config := utils.GetConfig()
	var connectErr error
	engine, connectErr = xorm.NewEngine(config.Db.Driver, config.Db.Connect)
	if connectErr != nil {
		return connectErr
	}
	err := engine.Sync2(new(schema.UserAgent), new(schema.Alive), new(schema.Statistics))
	if err != nil {
		log.Println(err)
		return fmt.Errorf("数据库同步表格失败")
	}

	if engine.Ping() != nil {
		return fmt.Errorf("数据库链接失败")
	}
	log.Printf("数据库连接成功")
	return nil
}

func GetDriver() *xorm.Engine {
	return engine
}
